package com.jhgsys.internal.sypq.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jhgsys.internal.sypq.entity.Notice;
import com.jhgsys.internal.sypq.mapper.NoticeMapper;
import com.jhgsys.internal.sypq.service.INoticeService;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.system.entity.User;
import com.jhgsys.internal.system.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import com.jhgsys.internal.common.entity.FebsConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 待办通知表 Service实现
 *
 * @author ganjun
 * @date 2024-11-30 21:43:28
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements INoticeService {
    @Autowired
    IUserService userService;

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param request QueryRequest
     * @param notice notice
     * @return IPage<Notice>
    */
    @Override
    public IPage<Notice> findNoticePage(QueryRequest request, Notice notice) {
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getDeletedFlg, 0);
        // TODO 设置查询条件

        Page<Notice> page = new Page<>(request.getPageNum(), request.getPageSize());
        FebsUtil.pageWrapper(page, request);
        return this.page(page, queryWrapper);
    }

    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param notice notice
     * @return List<Notice>
     */
    @Override
    public List<Notice> findNoticeList(Notice notice) {
	    LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getDeletedFlg, 0);
		// TODO 设置查询条件
		return this.baseMapper.selectList(queryWrapper);
    }

    /**
    * 根据ID查询
    * @author ganjun
    * @date 2024-11-30 21:43:28
    * @param id
    * @return Notice
    */
    @Override
    public Notice findNoticeById(String id){
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param notice notice
     */
    @Override
    @Transactional
    public boolean createNotice(Notice notice) {
        if(StringUtils.isNotEmpty(notice.getReceiveUserId()) && StringUtils.isEmpty(notice.getReceiveRealName())){
            List<User> users = userService.findUserByUserIds(Arrays.asList(notice.getReceiveUserId().split(",")));
            if(CollectionUtil.isNotEmpty(users)){
                notice.setReceiveRealName(users.stream().map(User::getUname).collect(Collectors.joining(",")));
            }
        }
        notice.setSendDate(new Date());
        notice.setDeletedFlg("0");
        notice.setStatus(0);
        return this.save(notice);
    }

    /**
     * 修改
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param notice notice
     */
    @Override
    @Transactional
    public boolean updateNotice(Notice notice) {
        return this.updateById(notice);
    }

    /**
     * 逻辑删除
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param notice notice
     * @param noticeIds noticeIds
     */
    @Override
    @Transactional
    public boolean deleteNotice(Notice notice,String noticeIds) {
        boolean result = false;
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<String> list = Arrays.asList(noticeIds.split(StringPool.COMMA));

        notice.setDeletedBy(user.getUserName());
        notice.setDeletedTime(new Date());
        notice.setDeletedFlg(FebsConstant.INVALID);
        int update = this.baseMapper.update(notice,new LambdaQueryWrapper<Notice>().in(Notice::getId,list));
        if (update > 0 ){
            result = true;
        }
        return result;
	}

    /**
    * 物理删除
    * @author ganjun
    * @date 2024-11-30 21:43:28
    * @param noticeIds noticeIds
    */
    @Override
    @Transactional
    public boolean physicallyDeleteNotice(String noticeIds) {
        List<String> list = Arrays.asList(noticeIds.split(StringPool.COMMA));
        LambdaQueryWrapper<Notice> wapper = new LambdaQueryWrapper<>();
        wapper.in(Notice::getId,list);
        return this.remove(wapper);
    }

    /**
     * 首页待办
     * @author ganjun
     * @date 2024-11-30 21:43:28
     * @param Notice notice
     */
    @Override
    @Transactional
    public List<Notice> todoList(Notice notice){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        String userId = user.getUserId();
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getDeletedFlg, 0);
        queryWrapper.and(wrap ->{
            wrap.eq(Notice::getReceiveUserId, "").or().like(Notice::getReceiveUserId, userId);
        });
//        queryWrapper.like(Notice::getReceiveUserId, userId);
        queryWrapper.eq(Notice::getStatus, 0);
        queryWrapper.orderByDesc(Notice::getCreatedTime);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 已读
     * @param noticeId
     */
    @Override
    public void done(String noticeId){
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Notice::getId,noticeId);
        queryWrapper.eq(Notice::getNoticeType, 1);
        queryWrapper.eq(Notice::getDeletedFlg, FebsConstant.VALID);
        Notice notice = this.baseMapper.selectOne(queryWrapper);
        if(notice != null){
            notice.setStatus(1);
            notice.setReceiveUserId(user.getUserId());
            notice.setReceiveRealName(user.getUserName());
            notice.setReceiveDate(new Date());
            this.baseMapper.updateById(notice);
        }
    }

    /**
     * 当待办处理完成后，将通知变成已读
     */
    @Override
    public void dealDone(Notice n){
        LambdaQueryWrapper<Notice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Notice::getNoticeType, 2);
        queryWrapper.eq(Notice::getStatus, 0);
        queryWrapper.eq(Notice::getNoticeTitle, n.getNoticeTitle());
        queryWrapper.eq(Notice::getBizId, n.getBizId());
        queryWrapper.eq(Notice::getDeletedFlg, FebsConstant.VALID);
        List<Notice> notices = baseMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(notices)){
            for(Notice notice : notices){
                notice.setStatus(1);
                baseMapper.updateById(notice);
            }
        }
    }
}
